<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="车次编号" prop="trainCode">
        <el-input
          v-model="queryParams.trainCode"
          placeholder="请输入车次编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查找</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleClear"
          v-hasPermi="['base:train-seat:remove']"
        >清空数据</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 三级折叠面板 -->
    <div class="train-seat-container" v-loading="loading">
      <el-collapse v-if="trainGroups && trainGroups.length > 0">
        <!-- 第一级：列车 -->
        <el-collapse-item v-for="train in trainGroups" :key="train.trainCode" :name="train.trainCode">
          <template slot="title">
            <div class="collapse-header">
              <span class="collapse-title">列车编号：{{ train.trainCode }}</span>
              <span class="collapse-count">共 {{ train.carriages && train.carriages.length || 0 }} 节车厢</span>
            </div>
          </template>

          <!-- 第二级：车厢 -->
          <el-collapse v-if="train.carriages && train.carriages.length > 0">
            <el-collapse-item v-for="carriage in train.carriages" :key="`${train.trainCode}-${carriage.carriageIndex}`">
              <template slot="title">
                <div class="collapse-header">
                  <span class="collapse-title">车厢号：{{ carriage.carriageIndex }}</span>
                  <span class="collapse-count">共 {{ carriage.seats && carriage.seats.length || 0 }} 个座位</span>
                </div>
              </template>

              <!-- 第三级：座位列表 -->
              <el-table :data="carriage.seats || []" border stripe>
                <el-table-column label="排号" align="center" prop="row" />
                <el-table-column label="列号" align="center" prop="col" />
                <el-table-column label="座位类型" align="center" prop="seatType">
                  <template slot-scope="scope">
                    <dict-tag :options="dict.type.seat_type" :value="scope.row.seatType"/>
                  </template>
                </el-table-column>
                <el-table-column label="同车厢座序" align="center" prop="carriageSeatIndex" />
<!--                <el-table-column label="操作" align="center" width="150">-->
<!--                  <template slot-scope="scope">-->
<!--                    <el-button-->
<!--                      size="mini"-->
<!--                      type="text"-->
<!--                      icon="el-icon-edit"-->
<!--                      @click="handleUpdate(scope.row)"-->
<!--                      v-hasPermi="['base:train-seat:edit']"-->
<!--                    >修改</el-button>-->
<!--                    <el-button-->
<!--                      size="mini"-->
<!--                      type="text"-->
<!--                      icon="el-icon-delete"-->
<!--                      @click="handleDelete(scope.row)"-->
<!--                      v-hasPermi="['base:train-seat:remove']"-->
<!--                    >删除</el-button>-->
<!--                  </template>-->
<!--                </el-table-column>-->
              </el-table>
            </el-collapse-item>
          </el-collapse>
          <div v-else class="empty-data">该列车暂无车厢数据</div>
        </el-collapse-item>
      </el-collapse>
      <div v-else-if="!loading" class="empty-data">暂无列车数据</div>
    </div>

    <pagination
      v-show="trainTotal>0"
      :total="trainTotal"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改列车座位对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="车次编号" prop="trainCode">
          <el-input v-model="form.trainCode" placeholder="请输入车次编号" />
        </el-form-item>
        <el-form-item label="厢序" prop="carriageIndex">
          <el-input-number v-model="form.carriageIndex" :min="1" placeholder="请输入厢序" />
        </el-form-item>
        <el-form-item label="排号" prop="row">
          <el-input v-model="form.row" placeholder="请输入排号，如：01, 02" />
        </el-form-item>
        <el-form-item label="列号" prop="col">
          <el-input v-model="form.col" placeholder="请输入列号" />
        </el-form-item>
        <el-form-item label="座位类型" prop="seatType">
          <el-select v-model="form.seatType" placeholder="请选择座位类型">
            <el-option
              v-for="dict in dict.type.seat_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="座序" prop="carriageSeatIndex">
          <el-input-number v-model="form.carriageSeatIndex" :min="1" placeholder="请输入同车厢座序" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 清空对话框 -->
    <el-dialog :title="title" :visible.sync="clearOpen" width="500px" append-to-body>
      <el-form ref="clearForm" :model="clearForm" :rules="clearRules" label-width="80px">
        <el-form-item label="密码" prop="password">
          <el-input v-model="clearForm.password" type="password" placeholder="请输入登录密码" show-password />
          <div style="color: #F56C6C; font-size: 12px; margin-top: 8px;">提示：清空操作将删除所有列车座位数据且不可恢复，请谨慎操作！</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitClearForm">确 定</el-button>
        <el-button @click="cancelClear">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTrainSeat, getTrainSeat, delTrainSeat, addTrainSeat, updateTrainSeat, listTrainSeatGroup, clearTrainSeat } from "@/api/base/train-seat";

export default {
  name: "Train-seat",
  dicts: ['seat_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 列车总数（用于分页）
      trainTotal: 0,
      // 列车座位表格数据
      trainSeatList: [],
      // 按列车分组的数据
      trainGroups: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,  // 每页显示10个列车
        trainCode: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        trainCode: [
          { required: true, message: "车次编号不能为空", trigger: "blur" }
        ],
        carriageIndex: [
          { required: true, message: "厢序不能为空", trigger: "blur" }
        ],
        row: [
          { required: true, message: "排号不能为空", trigger: "blur" }
        ],
        col: [
          { required: true, message: "列号不能为空", trigger: "blur" }
        ],
        seatType: [
          { required: true, message: "座位类型不能为空", trigger: "change" }
        ]
      },
      // 清空对话框
      clearOpen: false,
      // 清空表单
      clearForm: {
        password: undefined
      },
      // 清空表单校验
      clearRules: {
        password: [
          { required: true, message: "请输入登录密码", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询列车座位列表 */
    getList() {
      this.loading = true;
      listTrainSeatGroup(this.queryParams).then(response => {
        // 若依框架返回格式通常是 {code: 200, msg: "操作成功", data: {...}}
        // 所以需要正确访问数据
        console.log("API返回数据结构:", response); // 调试用

        // 正确获取返回数据
        if (response.code === 200) {
          // 方式1: 若后端data直接包含trainGroups数组
          if (Array.isArray(response.data)) {
            this.trainGroups = response.data;
            this.trainTotal = response.total || this.trainGroups.length;
          }
          // 方式2: 若后端data包含{data:[], trainTotal:n}
          else if (response.data && response.data.data) {
            this.trainGroups = response.data.data;
            this.trainTotal = response.data.trainTotal || this.trainGroups.length;
          }
          // 方式3: 若后端rows字段包含数据(类似常规列表接口)
          else if (response.rows) {
            this.trainGroups = response.rows;
            this.trainTotal = response.total || this.trainGroups.length;
          }
          else {
            this.trainGroups = [];
            this.trainTotal = 0;
            console.error("未能识别的数据结构:", response);
          }
        } else {
          this.trainGroups = [];
          this.trainTotal = 0;
        }

        // 确保每个train对象都有carriages属性
        this.trainGroups.forEach(train => {
          if (!train.carriages) {
            train.carriages = [];
          }

          // 确保每个carriage对象都有seats属性
          train.carriages.forEach(carriage => {
            if (!carriage.seats) {
              carriage.seats = [];
            }
          });
        });

        this.loading = false;
      }).catch(error => {
        console.error("获取列车座位数据失败:", error);
        this.trainGroups = [];
        this.trainTotal = 0;
        this.loading = false;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        trainCode: null,
        carriageIndex: null,
        row: null,
        col: null,
        seatType: null,
        carriageSeatIndex: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加列车座位";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getTrainSeat(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改列车座位";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTrainSeat(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTrainSeat(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除列车座位编号为"' + ids + '"的数据项？').then(function() {
        return delTrainSeat(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 清空按钮操作 */
    handleClear() {
      this.clearOpen = true;
      this.title = "清空列车座位数据";
    },
    /** 提交清空表单 */
    submitClearForm() {
      this.$refs["clearForm"].validate(valid => {
        if (valid) {
          this.$modal.confirm('是否确认清空所有列车座位数据？').then(() => {
            return clearTrainSeat({ password: this.clearForm.password });
          }).then(response => {
            if (response.code === 200) {
              this.$modal.msgSuccess("清空成功");
              this.clearOpen = false;
              this.resetClearForm();
              this.getList();
            } else {
              this.$modal.msgError(response.msg || "清空失败");
            }
          }).catch(error => {
            console.error("清空失败:", error);
            this.$modal.msgError("清空失败：" + (error.msg || "未知错误"));
          });
        }
      });
    },
    /** 取消清空 */
    cancelClear() {
      this.clearOpen = false;
      this.resetClearForm();
    },
    /** 重置清空表单 */
    resetClearForm() {
      this.clearForm = {
        password: undefined
      };
      this.resetForm("clearForm");
    }
  }
};
</script>

<style scoped>
.train-seat-container {
  margin-bottom: 20px;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

/* 自定义折叠面板样式 */
::v-deep .el-collapse {
  border: none;
}

::v-deep .el-collapse-item__header {
  background: linear-gradient(to right, #f9f9f9, #ffffff);
  height: 50px;
  padding: 0 15px;
  border-left: 4px solid #409EFF;
  border-bottom: 1px solid #EBEEF5;
  transition: all 0.3s;
}

::v-deep .el-collapse-item__header:hover {
  background: linear-gradient(to right, #f0f5ff, #ffffff);
}

::v-deep .el-collapse-item__arrow {
  color: #409EFF;
  font-size: 16px;
  transition: transform 0.3s;
}

::v-deep .el-collapse-item__wrap {
  border: none;
  background-color: #fafafa;
}

/* 二级折叠面板样式 */
::v-deep .el-collapse .el-collapse .el-collapse-item__header {
  background: #f5f7fa;
  border-left: 3px solid #67C23A;
  height: 45px;
  margin: 5px 10px;
  border-radius: 4px;
}

::v-deep .el-collapse .el-collapse .el-collapse-item__header:hover {
  background: #f0f9eb;
}

::v-deep .el-collapse .el-collapse .el-collapse-item__wrap {
  background: #ffffff;
  padding: 0 15px;
  margin: 0 10px;
  border-radius: 4px;
}

.collapse-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.collapse-title {
  font-weight: 600;
  font-size: 16px;
  color: #303133;
}

.collapse-count {
  color: #606266;
  font-size: 14px;
  background: #f0f2f5;
  padding: 2px 10px;
  border-radius: 12px;
}

/* 嵌套表格样式调整 */
.el-table {
  margin: 10px 0;
  border-radius: 6px;
  overflow: hidden;
}

::v-deep .el-table th {
  background-color: #f5f7fa;
}

::v-deep .el-table--striped .el-table__body tr.el-table__row--striped td {
  background-color: #fafafa;
}

/* 调整折叠面板内部边距 */
.el-collapse-item__content {
  padding: 15px;
}

/* 调整分页组件样式 */
.pagination-container {
  margin-top: 20px;
}

/* 添加空数据提示样式 */
.empty-data {
  padding: 30px;
  text-align: center;
  color: #909399;
  font-size: 14px;
  background-color: #f8f8f9;
  border-radius: 6px;
  margin: 10px 0;
  border: 1px dashed #e0e0e0;
}
</style>
